const { mergeAgent, logger, cloudApiClient } = require('../utils');

module.exports = (app) => {
  // 扩展信息列表
  app.post(`${process.env.VUE_APP_BASE_API}/external/list`, async (req, res) => {
    const { userInfo, token } = req;
    const targetUser = userInfo;
    if (targetUser) {
      // Agent.ProxyOrganizationOpenId、Agent. ProxyOperator.OpenId、Agent.AppId 和 Agent.ProxyAppId 均必填
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
          ProxyAppId: targetUser.proxyAppId,
        }),
        Version: '2021-05-26',
      };
      // console.log('targetUser===', targetUser, params);
      cloudApiClient.DescribeExtendedServiceAuthInfo(params).then(
        (data) => {
          // console.log('DescribeExtendedServiceAuthInfo====', data);
          res.json({
            code: 20000,
            data,
          });
        },
        (err) => {
          logger.error({
            ...params,
            Action: 'DescribeExtendedServiceAuthInfo',
            message: err,
          });
          res.json(err);
        },
      );
    } else {
      logger.error({
        Action: 'external/list',
        token,
        message: '用户信息不存在',
      });
      res.json({
        code: 500,
        message: '用户信息不存在',
      });
    }
  });


  // 修改企业扩展服务
  app.post(`${process.env.VUE_APP_BASE_API}/external/update`, async (req, res) => {
    const { userInfo, token, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      // Agent.ProxyOrganizationOpenId、Agent. ProxyOperator.OpenId、Agent.AppId 和 Agent.ProxyAppId 均必填
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
          ProxyAppId: targetUser.proxyAppId,
        }),
        ...body,
        Version: '2021-05-26',
      };
      // console.log('targetUser===', targetUser, params);
      cloudApiClient.ModifyExtendedService(params).then(
        (data) => {
          // console.log('ModifyExtendedService====', data);
          res.json({
            code: 20000,
            data,
          });
        },
        (err) => {
          logger.error({
            ...params,
            Action: 'ModifyExtendedService',
            message: err,
          });
          res.json(err);
        },
      );
    } else {
      logger.error({
        Action: 'external/list',
        token,
        message: '用户信息不存在',
      });
      res.json({
        code: 500,
        message: '用户信息不存在',
      });
    }
  });
};
